<?php
/**
 * 可升级商品升级处理
 */
namespace App\Http\Services;

use App\Http\Model\GoodsLevel;
use App\Http\Model\Hint;
use App\Http\Model\Mall;
use App\Http\Model\User;
use App\Http\Model\UserCoolval;
use App\Http\Model\UserGoodsIncome;
use App\Modules\Relationship\Models\QueueExecModel;
use Illuminate\Support\Facades\DB;


class GoodsIncomeServices extends CommonServices
{
    private $modelCoolval;

    // 商品(坐骑)在线佩戴任务 KEY
    const TASK_USER_GOODSINC = 'UserGoodsIncomeChange';
    const TASK_USER_GOODSINC_CYCLE = 30; //3分钟，180秒 一个周期

    private $useIncTimekey = 'UserGoodsIncomeChange:%s:$s';//type:string  UserGoodsIncomeChange:UId:GID = TIME

    public function __construct()
    {
        $this->modelCoolval = new UserCoolval();
    }

    /*
     * 装扮升级
        1、定时任务全表扫描在线用户
        2、穿戴装扮是否存在升级装扮
        3、压入延时 X 分钟 队列，延时执行1次
     */

    public function taskUserGoodsIncomeChange($userId, $goodsId, $changeDesc)
    {

    }

    /**
     * 任务消费
     * @param $parms
     */
    public function handUserGoodsIncomeChange($parms)
    {
        $data = $parms;
        $UID = $data['user_id'] ?? 0;
        $GID = $data['goods_id'] ?? 0;
        $desc = $data['desc'] ?? '';
        $time = $data['exec_time'] ?? 0;

        $data = [];
        $data['user_id'] = $UID;
        $data['goods_id'] = $GID;
        $data['desc'] = $desc;
        $data['exec_time'] = $time;
        $res = $this -> doUserGoodsIncomeChange($data);
        /*if ($res && $res['code'] ==Hint::SAY_HELLO_FAIL){
            taskUserGoodsIncomeChange();
        }*/
        $this->queueExecModel = new queueExecModel();
        if ($res && $res['code']==Hint::SUCCESS){
            $this->queueExecModel->updateRecordByCode(md5(json_encode($parms)),1);
        }else{
            $this->queueExecModel->updateRecordByCode(md5(json_encode($parms)),2);
        }

        return true;
    }


    /**
     * 可升级商品佩戴经验变更
     */
    public function doUserGoodsIncomeChange($parms)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        $error = 'ok';

        $UID = $parms['user_id'] ?? 0;
        $GID = $parms['goods_id'] ?? 0;
        $desc = $parms['desc'] ?? '可升级商品佩戴经验变更';
        $time = $parms['exec_time'] ?? 0;

        try {
            if ($UID<=0){
                $code = Hint::PARAM_ERROR;
                $msg = '用户ID必需';
                throw new \Exception($msg);
            }

            if ($GID<=0){
                $code = Hint::PARAM_ERROR;
                $msg = '商品ID必需';
                throw new \Exception($msg);
            }

            if ($time<=0){
                $code = Hint::PARAM_ERROR;
                $msg = '任务开始时间必需';
                throw new \Exception($msg);
            }

            $runTime = $time + self::TASK_USER_GOODSINC_CYCLE;// 值
            if ( $runTime > time() ){
                $code = Hint::SAY_HELLO_FAIL;//10018
                $msg = '任务执行时间未到期';
                // 压入重新执行
                throw new \Exception($msg);
            }
            // 是否在线
            $this->userModel = new User();
            //$list = $this->userModel->getOnlineUserArr();
            //print_r($list);
            $ifOnline = intval($this->userModel->checkUserOnlineStatus($UID));//1=在线 0=不在线
            if (!$ifOnline){
                $code = Hint::PARAM_ERROR;//10018
                $msg = '用户已不在线';
                // 压入重新执行
                throw new \Exception($msg);
            }

            # TODO 多任务处理

            //是否佩戴、
            //佩戴坐骑是否可升级
            $modelMall = new Mall();
            $goodsInfo = $modelMall -> getUserUpgradeGoodsAttire($UID, $GID);
            if (empty($goodsInfo)){
                $msg = '无佩戴可升级礼物';
                throw new \Exception($msg);
            }

            // 计算得分系数-每3分钟X经验
            $inc = 0;
            $cool_val = $this->modelCoolval -> getUserCoolval($UID);
            $level_info = $this->modelCoolval -> getLevelByVal($cool_val);
            if ($level_info){
                $content = $level_info['content'] ? json_decode($level_info['content'], true) : [];
                $inc = $content['coolval'] ?? 0;
            }
            $data['level_info'] = $level_info;
            if ( $inc <=0 ){
                $msg = '无需添加升级商品经验';
                throw new \Exception('无需添加升级商品经验');
            }
            $modelUserGoodsIncome = new UserGoodsIncome();
            $ifUserGoodsInc = $modelUserGoodsIncome -> ifUserGoodsIncome($UID, $GID);
            DB::beginTransaction();
            if ($ifUserGoodsInc){
                $ifInc = $modelUserGoodsIncome -> incUserGoodsIncome($UID, $GID, $inc);
            }else{
                $dataInc = [];
                $dataInc['user_id'] = $UID;
                $dataInc['goods_id'] = $GID;
                $dataInc['income'] = $inc;
                $dataInc['add_time'] = $dataInc['edit_time'] = time();
                $ifInc = $modelUserGoodsIncome -> addUserGoodsIncome($dataInc);
            }
            if (!$ifInc){
                $code = Hint::PARAM_ERROR;
                $msg = '商品经验值更新失败';
                throw new \Exception($msg);
            }
            $dataLog = [];
            $dataLog['user_id'] = $UID;
            $dataLog['goods_id'] = $GID;
            $dataLog['change_inc'] = $inc;
            $dataLog['desc'] = $desc;
            $dataLog['add_time'] = time();
            $modelUserGoodsIncome -> addUserGoodsIncomeLog($dataLog);


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            $error = $e->getMessage() . '-line:' . $e->getLine();
            $code = ($code != Hint::SUCCESS) ? $code : Hint::ERROR;
            $msg .= '-可升级商品佩戴经验变更失败';
        }
        write_log(
            'GoodsIncomeServices'.(isCli()?'-cli':''),
            ($code == Hint::SUCCESS ? '[INFO]':'[ERROR]').' doUserGoodsIncomeChange',
            ['error'=>$error, 'args'=>func_get_args()]
        );

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取用户
     */
    public function getUserGoodsUpgradeInfo($userId, $GID)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];


        $modelUserGoodsIncome = new UserGoodsIncome();
        $income = $modelUserGoodsIncome-> getUserGoodsIncome($userId, $GID);
        $upgradeInfo = $modelUserGoodsIncome-> getUpgradeInfoByInc($income, $GID);

        $data['income'] = $income;
        $data['upgrade_info'] = $upgradeInfo;

        return compact('code', 'msg', 'data');
    }



















}